﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelDna;
using ExcelDna.Integration;
using System.Windows.Forms;

namespace MFE
{
    public class Class1
    {
        [ExcelFunction(Description = "Calcula Fecha de Parto")]
        public static DateTime FechaParto(DateTime fur)
        {
            if (fur > DateTime.Now)
            {
                MessageBox.Show("La fecha de la Fur no puede ser superior a la Actual" + Environment.NewLine + "Fecha Actual: " + DateTime.Now);
                return Convert.ToDateTime("00/00/0000");
            }
            DateTime fecha;
            fecha = fur.AddDays(289);
            return fecha;
        }
        [ExcelFunction(Description = "Quita Apostrofe en la Fecha")]
        public static DateTime QAFecha(string celda)
        {
            DateTime Fecha;
            char[] MyChar = { '´' };
            string Celda1 = celda.TrimStart(MyChar);
            Fecha = Convert.ToDateTime(celda);
            return Fecha;
        }
        [ExcelFunction(Description = "Calcula Edad")]
        public static int EdadActual(DateTime celda)
        {
            DateTime Fecha = DateTime.Now;
            int f = 0;
            f = DateTime.Now.Subtract(celda).Days / 365;
            return f;
        }

        [ExcelFunction(Description = "Calcula EG al Ingreso")]
        public static int EGIngreso_ddmmaaaa(int d, int m, int a, int d1, int m1, int a1)
        {
            DateTime EGFecha = Convert.ToDateTime(d + "/" + m + "/" + a);
            DateTime EGFecha1 = Convert.ToDateTime(d1 + "/" + m1 + "/" + a1);
            int EGFecha3;
            string fes = Convert.ToString(EGFecha.ToShortDateString());
            string fes1 = Convert.ToString(EGFecha1.ToShortDateString());
            DialogResult F = MessageBox.Show("Fur: " + fes + Environment.NewLine + "FI: " + fes1, "Verificar", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (F != DialogResult.OK) { MessageBox.Show("Cambie los Valores" + Environment.NewLine + "DD-MM-AAAA"); return 0; };
            EGFecha3 = EGFecha1.Subtract(EGFecha).Days / 7;
            if (EGFecha3 < 0)
            {
                MessageBox.Show("Verificar la casilla SEMANAS DE GESTACION AL INGRESO AL PROGRAMA: La fecha de captacion no puede ser Menor que la Fur", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return -1;
            };
            if (EGFecha3 > 43)
            {
                MessageBox.Show("Verificar la casilla SEMANAS DE GESTACION AL INGRESO AL PROGRAMA: La fecha de captacion no puede ser Menor que la Fur mayor que 43 semanas", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return -1;
            };
            return EGFecha3;
        }
        [ExcelFunction(Description = "Valida el diligenciamiento del riesgo")]
        public static string Vriesgo(object[] a)
        {
            string errores = null;
            int cell = 0;
            foreach (object a1 in a)
            {
                try
                {
                    cell += Convert.ToInt32(a1);
                }
                catch (Exception ex)
                {
                    cell += 0;
                }
            };
            MessageBox.Show(Convert.ToString(cell));
            if (cell != 1)
            {
                errores = "Mala clasificacion del riesgo revise";
                if (cell <= 0)
                {
                    errores += ", No dilingeciado";
                };
                if (cell >= 2)
                {
                    errores += ", Coloco mas de un riesgo";
                };
                return errores;

            };
            return "Clasificacion del riesgo ok";
        }
        [ExcelFunction(Description = "Calcula Edad Gestacional")]
        public static int EG_ddmmaaaa(int d, int m, int a)
        {
            DateTime fur = Convert.ToDateTime(d + "/" + m + "/" + a);
            if (fur > DateTime.Now)
            {
                MessageBox.Show("La fecha de la Fur no puede ser superior a la Actual" + Environment.NewLine + "Fecha Actual: " + DateTime.Now);
                return -1;
            }
            int eg;
            eg = DateTime.Now.Subtract(fur).Days / 7;
            return eg;
        }
        [ExcelFunction(Description = "Proximo Control")]
        public static string Vcontrol(object[] y)
        {
            string errores = "";
            int mes = 0;
            DateTime fecha = new DateTime();
            foreach (object y1 in y)
            {
                try
                {
                    mes++;
                    if (y1 is ExcelEmpty) { errores = errores + "El control: " + mes + " no tiene datos!!, "; };
                    fecha = DateTime.FromOADate((double)y1);


                }
                catch (Exception ex)
                {
                    fecha = fecha;
                }
            }

            //MessageBox.Show(Convert.ToString(fecha)+ " | "+ mes + " | ");
            return errores;

        }
        [ExcelFunction(Description = "Llema espacion en blanco")]
        public static string LlenaBlancos(object[] y)
        {
            string blanco = "";
            int y2 = -1;
            foreach (object y1 in y)
            {
                try
                {
                    y2++;
                    blanco = (string)y1;
                    return blanco;
                }
                catch (Exception ex)
                {

                    blanco = blanco;
                }
            }

            //MessageBox.Show(Convert.ToString(fecha)+ " | "+ mes + " | ");
            return blanco;

        }

        //Clase helper
        // Here is the helper class - add to it or change as you require
        internal static class Optional
        {
            internal static string Check(object arg, string defaultValue)
            {
                if (arg is string)
                    return (string)arg;
                else if (arg is ExcelMissing)
                    return defaultValue;
                else
                    return arg.ToString();  // Or whatever you want to do here....

                // Perhaps check for other types and do whatever you think is right ....
                //else if (arg is double)
                //    return "Double: " + (double)arg;
                //else if (arg is bool)
                //    return "Boolean: " + (bool)arg;
                //else if (arg is ExcelError)
                //    return "ExcelError: " + arg.ToString();
                //else if (arg is object[,])
                //    // The object array returned here may contain a mixture of types,
                //    // reflecting the different cell contents.
                //    return string.Format("Array[{0},{1}]", 
                //      ((object[,])arg).GetLength(0), ((object[,])arg).GetLength(1));
                //else if (arg is ExcelEmpty)
                //    return "<<Empty>>"; // Would have been null
                //else if (arg is ExcelReference)
                //  // Calling xlfRefText here requires IsMacroType=true for this function.
                //				return "Reference: " + 
                //                     XlCall.Excel(XlCall.xlfReftext, arg, true);
                //			else
                //				return "!? Unheard Of ?!";
            }

            internal static double Check(object arg, double defaultValue)
            {
                if (arg is double)
                    return (double)arg;
                else if (arg is ExcelMissing)
                    return defaultValue;
                else
                    throw new ArgumentException();  // Will return #VALUE to Excel

            }

            // This one is more tricky - we have to do the double->Date conversions ourselves
            internal static DateTime Check(object arg, DateTime defaultValue)
            {
                if (arg is double)
                    return DateTime.FromOADate((double)arg);    // Here is the conversion
                else if (arg is string)
                    return DateTime.Parse((string)arg);
                else if (arg is ExcelMissing)
                    return defaultValue;

                else
                    throw new ArgumentException();  // Or defaultValue or whatever
            }

        }




        [ExcelCommand(MenuName = "Comandos Amar", MenuText = "Semanas al Ingreso")]
        public static void MyMacro()
        {
            ////.... 
            //Excel.Application app = (Excel.Application)ExcelDna.Integration.ExcelDnaUtil.Application;
            //Excel.Range activeCell = app.ActiveCell;
            ////if (activeCell.Value != 1) { activeCell.Font.Bold = true; activeCell.Font.ColorIndex = 5; };
            ////if (activeCell.Value is ExcelEmpty) { };
            //activeCell.FormulaR1C1 = "=Vcontrol(RC[-7]:RC[-1])";


        } 
    }
}
